package com.example.ymm.component.mqtt;

import com.alibaba.fastjson.JSONObject;
import com.example.ymm.modules1.entity.my.sys.iot.IotTag;
import com.example.ymm.modules1.entity.my.sys.iot.ViewIotTag;
import com.example.ymm.modules1.query.sys.iot.IotTagQueryCriteria;
import com.example.ymm.modules1.service.sys.iot.IotTagService;
import com.example.ymm.util.DateKit;
import com.example.ymm.util.EmailUtil;
import com.example.ymm.util.RedisUtil;
import com.example.ymm.util.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Configuration
@ConfigurationProperties(prefix = "mqtt")
@Profile("prod-new")
public class MqttConfig {
   // dev   prod-new
    @Autowired
    IotTagService iotTagService;
    @Value("${spring.profiles.active}")
    String PD_MATCH;
    @Autowired
    private RedisUtil redisUtil;

    private String brokerUrl;
    private String clientId;
    private String username;
    private String password;
    private String defaultTopic;
    private int qos;
    private int keepAlive;

    // Getters and Setters
    public String getBrokerUrl() {
        return brokerUrl;
    }

    public void setBrokerUrl(String brokerUrl) {
        this.brokerUrl = brokerUrl;
    }

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDefaultTopic() {
        return defaultTopic;
    }

    public void setDefaultTopic(String defaultTopic) {
        this.defaultTopic = defaultTopic;
    }

    public int getQos() {
        return qos;
    }

    public void setQos(int qos) {
        this.qos = qos;
    }

    public int getKeepAlive() {
        return keepAlive;
    }

    public void setKeepAlive(int keepAlive) {
        this.keepAlive = keepAlive;
    }

    /**
     * 创建 MQTT 客户端工厂
     */
    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        MqttConnectOptions options = new MqttConnectOptions();
        options.setServerURIs(new String[]{brokerUrl});
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setKeepAliveInterval(keepAlive);
        options.setAutomaticReconnect(true);
        factory.setConnectionOptions(options);
        return factory;
    }

    /**
     * 接收消息的通道
     */
    @Bean
    public MessageChannel mqttInputChannel() {
        return new DirectChannel();
    }

    /**
     * 创建 MQTT 消息驱动的通道适配器（用于接收消息）
     */
    @Bean
    public MqttPahoMessageDrivenChannelAdapter inbound() {
        long l = System.currentTimeMillis();
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                clientId +PD_MATCH+l, mqttClientFactory(), defaultTopic);
        adapter.setCompletionTimeout(5000);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setQos(qos);
        adapter.setOutputChannel(mqttInputChannel());
        return adapter;
    }

    /**
     * 消息处理器（处理接收到的消息）
     */
    @Bean
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public MessageHandler handler() {
        return message -> {
            String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
            String content = message.getPayload().toString();
            // 这里可以添加自定义的消息处理逻辑
            try{
              //  if ("dev".equals(PD_MATCH)) {//prod-new  dev
                    Date date = new Date();
                    String s = DateKit.dateFormat(date, "yyyy-MM-dd-HH-mm-ss");
                    redisUtil.set("close_tag:"+s, content);
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    String tagMac=jsonObject.getString("tagMac");

                    if(UtilValidate.isNotEmpty(jsonObject)){
                        System.out.println("---topic:"+topic);
                        System.out.println("---接受到-监听电量-主题消息:"+jsonObject);
                        //电量
//                        if(jsonObject.containsKey("battery")){
//                            Integer battery = jsonObject.getInteger("battery");
//                            tag.setBattery(battery);
//                            iotTagService.saveOrUpdate(tag);
//                        }
                        //熄灯
                        if(UtilValidate.isNotEmpty(jsonObject.getString("cmdType"))){
                            log.info("收到消息 - 关灯消息: " + topic + ", 内容: " + content);

                            String cmdType = jsonObject.getString("cmdType");
                            String batchNo = jsonObject.getString("batchNo");
                            if("upload_tag_light_turn_off".equals(cmdType)){
                                System.out.println("--tagMac:"+tagMac);
                                ViewIotTag tag = iotTagService.getDetail(tagMac);
                                if(tag.getStatus() == 1){
                                    tag.setStatus(0);
                                    iotTagService.saveOrUpdate(tag);
                                }

                                if(UtilValidate.isNotEmpty(tag.getShelfMac())){
                                    //查询 对应巷道灯 下所有 标签是否关闭
                                    IotTagQueryCriteria criteria=new IotTagQueryCriteria();
                                    criteria.setTagMac(tag.getShelfMac());
                                    List<IotTag> iotTags = iotTagService.shelfTags(criteria);
                                    if(UtilValidate.isEmpty(iotTags)){
                                        boolean b = redisUtil.setIfAbsent(batchNo, batchNo, 1, TimeUnit.MINUTES);
                                        log.info("--锁住批次号1分钟："+b);
                                        if(b){
                                            log.info("--关闭巷道睡眠 剩余标签数量："+iotTags.size());
                                            Thread.sleep(200);
                                            log.info("--关闭巷道灯："+tag.getShelfMac()+";电子标签："+tagMac);
                                            JSONObject jsonObject1 = iotTagService.closeTag(tag.getShelfMac(),tag.getHouseLocationName());
                                            log.info("--巷道灯关闭成功"+jsonObject1);

                                            redisUtil.set("c_xd_tag:"+tag.getShelfMac()+":"+s,jsonObject1.toJSONString());
                                            redisUtil.remove(batchNo);
                                        }

                                    }

//                                    IotTag shelf_tag = iotTagService.getById(tag.getShelfMac());
//
//                                    if(UtilValidate.isNotEmpty(shelf_tag)&&shelf_tag.getStatus() == 1){
//                                        log.info("--关闭巷道睡眠200毫秒");
//                                        Thread.sleep(200);
//                                        log.info("--关闭巷道灯："+tag.getShelfMac()+";电子标签："+tagMac);
//                                        JSONObject jsonObject1 = iotTagService.closeTag(tag.getShelfMac());
//                                        log.info("--巷道灯关闭成功"+jsonObject1);
//
//                                        redisUtil.set("c_xd_tag:"+tag.getShelfMac()+":"+s,jsonObject1.toJSONString());
//                                    }
                                }
                            }

                        }else{
//                    if(UtilValidate.isNotEmpty(tag.getShelfMac())){
//                        log.info("--开启巷道灯："+tag.getShelfMac());
//                        iotTagService.openTag(tag.getShelfMac());
//                    }



                        }



                    }else{
                        EmailUtil.sendEmail("1055162826@qq.com","监听关灯 查找不到标签mac:"+tagMac,"环境："+PD_MATCH+";time="+ DateKit.getStringNowTime());
                    }
//                }else{
//                    log.info("--非生产环境不关闭巷道灯：");
//                }

            }catch (Exception e) {
                log.error("主题监听失败:"+e.getMessage(), e);
            }
        };
    }

    /**
     * 发送消息的通道
     */
    @Bean
    public MessageChannel mqttOutputChannel() {
        return new DirectChannel();
    }

//    /**
//     * 创建 MQTT 消息处理器（用于发送消息）
//     */
//    @Bean
//    @ServiceActivator(inputChannel = "mqttOutputChannel")
//    public MessageHandler mqttOutbound() {
//        MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
//                clientId + "_outbound", mqttClientFactory());
//        messageHandler.setAsync(true);
//        messageHandler.setDefaultTopic(defaultTopic);
//        messageHandler.setDefaultQos(qos);
//        return messageHandler;
//    }
}

